﻿
CREATE PROCEDURE [dbo].[CustomerReturnDocUpdate]
(--возврат от покупателя
	@DocDate smalldatetime,
	@DocNumber varchar(20),
	@ContragentDocDate smalldatetime, --дата чека
	@ContragentDocNumber varchar(20), --номер чека
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @orgDocTypeId int, @orgDocDate smalldatetime

SET NOCOUNT ON

IF (@ContragentDocDate Is Null) OR (@ContragentDocNumber Is Null)
OR (@Original_MD Is Null) OR (@DocDate Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @orgDocTypeId = DocTypeId, @orgDocDate = DocDate
FROM CA.Documents WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @ContragentDocDate Is Null OR @ContragentDocNumber Is Null
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Не указаны дата чека или номер чека!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SET @DocDate = dbo.NormalizeDate(@DocDate)

IF @ContragentDocDate > @DocDate
BEGIN
	SELECT @intErrCode = 4, 
	@strMsg = 'Дата чека больше даты возврата!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @orgDocTypeId <> 7
BEGIN
	SELECT @intErrCode = 5, 
	@strMsg = 'Неправильный тип документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @orgDocDate < @DocDate --новая дата больше старой
BEGIN--проверить чтобы не было расходов по партиям из документа между старой и новой датами
	IF EXISTS (
SELECT TOP (1) LD.Id
FROM CA.GoodsDocLines AS LS INNER JOIN
CA.GoodsDocLines AS LD ON LS.PartyId = LD.PartyId INNER JOIN
CA.Documents AS D ON LD.DocId = D.Id
WHERE (LS.DocId = @Original_Id) AND (LD.DocId <> @Original_Id) 
AND (D.DocDate >= @orgDocDate) AND (D.DocDate <= @DocDate) AND (LD.Qntty < 0)
	)
	BEGIN
		SELECT @intErrCode = 6, 
		@strMsg = 'По некоторым партиям из возврата были расходы между старой и новой датами возврата!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

	SET NOCOUNT OFF;
UPDATE [CA].[Documents] SET 
[DocDate] = @DocDate, 
[DocNumber] = @DocNumber, 
ContragentDocDate = @ContragentDocDate, 
ContragentDocNumber = @ContragentDocNumber, 
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id AND MD = @Original_MD;

SELECT Id, DocTypeId, DocDate, DocNumber, 
ContragentDocDate, ContragentDocNumber,
DepartmentUserId, 
Note, MD, MW FROM CA.Documents WHERE (Id = @Original_Id)
RETURN 0
